package cn.xiyue.production.ui;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import cn.xiyue.production.R;
import cn.xiyue.production.adapter.IBaseAdapter;
import cn.xiyue.production.annotation.ColumnName;

public class SmartTableView extends LinearLayout {

    List<TableColumn> columns;

    BaseAdapter adapter;

    public SmartTableView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOrientation(VERTICAL);
    }

    public <T> void setData(List<T> list, Class<T> c) {

        //通过反射获取Field
        initColumn(c);

        //排序
        Collections.sort(columns, (o1, o2) -> o1.index - o2.index);

        //表头
        addHeader(list);

        //数据列表
        initListView(list);
    }

    private <T> void initListView(List<T> list) {
        ListView listView = new ListView(getContext());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        listView.setLayoutParams(params);
        adapter = new IBaseAdapter<T>(list) {
            @Override
            public ViewHolder<T> getViewHolder() {
                return new ViewHolder<T>() {
                    public View root;
                    public List<TextView> textViews;

                    @Override
                    public View setData(T data) {
                        for (int i = 0; i < textViews.size(); i++) {
                            try {
                                Field field = columns.get(i).field;
                                field.setAccessible(true);
                                String s = field.get(data).toString();
                                textViews.get(i).setText(s);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                        return root;
                    }

                    @Override
                    public View init(ViewGroup root) {
                        LinearLayout layout = new LinearLayout(getContext());
                        //初始化一行的View
                        textViews = new ArrayList<>();
                        for (TableColumn column : columns) {
                            TextView textView = getTextView();
                            layout.addView(textView);
                            textViews.add(textView);
                        }
                        this.root = layout;
                        return this.root;
                    }
                };
            }
        };
        listView.setAdapter(adapter);
        addView(listView);
    }

    private <T> void initColumn(Class<T> c) {
        Field[] declaredFields = c.getDeclaredFields();
        columns = new ArrayList<>();
        for (Field field : declaredFields) {
            ColumnName columnName = field.getAnnotation(ColumnName.class);
            if (columnName != null) {
                columns.add(new TableColumn(columnName.value(), field, columnName.index(), columnName.sort()));
            }
        }
    }

    private <T> void addHeader(List<T> list) {
        //添加表头
        LinearLayout linearLayout = new LinearLayout(getContext());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100, 1);
        for (TableColumn column : columns) {
            TextView textView = new TextView(getContext());
            textView.setText(column.name);
            textView.setGravity(Gravity.CENTER);
            textView.setTextColor(Color.BLACK);
            textView.setTextSize(18);
            textView.setLayoutParams(lp);
//            textView.setBackground(getResources().getDrawable(R.drawable.list_bg));

            if (column.sort) {
                textView.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.arrow2), null);
                textView.setCompoundDrawablePadding(-100);

                textView.setOnClickListener(v -> {
                    sort(list, column, column.desc);
                    column.desc = !column.desc;
                });
            }
            column.header = textView;
            linearLayout.addView(textView);
        }
        addView(linearLayout);
    }

    private <T> void sort(List<T> list, TableColumn column, boolean desc) {
        //Number类型按数字排序，否则按字符串
        Collections.sort(list, (o1, o2) -> {
            try {
                Object f1 = column.field.get(o1);
                Object f2 = column.field.get(o2);
                if (f1 instanceof Number && f2 instanceof Number) {
                    return desc ? ((Number) f2).intValue() - ((Number) f1).intValue() : ((Number) f1).intValue() - ((Number) f2).intValue();
                }
                return desc ? f2.toString().compareTo(f1.toString()) : f1.toString().compareTo(f2.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        });
        adapter.notifyDataSetChanged();
        int id = desc ? R.drawable.arrow1 : R.drawable.arrow2;
        String s = desc ? "降序" : "升序";
        column.header.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(id), null);
        Toast.makeText(getContext(), "按“" + column.name + "” " + s, Toast.LENGTH_SHORT).show();
    }

    static class TableColumn {
        public String name;
        public Field field;
        public int index;
        public boolean sort;
        public TextView header;
        public boolean desc = true;

        public TableColumn(String name, Field field, int index, boolean sort) {
            this.name = name;
            this.field = field;
            this.index = index;
            this.sort = sort;
        }
    }

    private TextView getTextView() {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
        TextView textView = new TextView(getContext());
        textView.setPadding(0, 30, 0, 30);
        textView.setGravity(Gravity.CENTER);
        textView.setLayoutParams(lp);
        return textView;
    }
}
